import { ConfigService } from '../common/config.service';
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Rx';
@Injectable()
export class BaseService {
  constructor(protected http: Http, protected config: ConfigService) { }
  protected query(url: any, params: any, pageNum: number, pageSize: number): Observable<any> {
    const u = typeof url === 'string' ? url.indexOf('http://') > -1 ? url : this.config.get('url') + '?' + url : typeof url === 'object' ?
      url.host ? url.host + '?service=' + url.service + '&method=' + url.method : this.config.get('url') + '?service=' +
        url.service + '&method=' + url.method : '';
    if (pageNum && pageSize) {
      if (params) {
        params.pageNum = pageNum;
        params.pageSize = pageSize;
      } else {
        params = {
          pageNum: pageNum,
          pageSize: pageSize
        };
      }
    }
    return this.http.post(u, params).map((res: Response) => {
      const body = res.json();
      return body.info || [];
    }).catch(this.handleError);
  }
  protected submit(url: any, params: any): Observable<any> {
    const u = typeof url === 'string' ? url.indexOf('http://') > -1 ? url : this.config.get('url') + '?' + url : typeof url === 'object' ?
      url.host ? url.host + '?service=' + url.service + '&method=' + url.method : this.config.get('url') + '?service=' +
        url.service + '&method=' + url.method : '';
    return this.http.post(u, params).map((res: Response) => {
      return res.json();
    }).catch(this.handleError);
  }
  private handleError(error: Response | any) {
    let errMsg: string;
    if (error instanceof Response) {
      const body = error.json() || '';
      const err = body.error || JSON.stringify(body);
      errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
    } else {
      errMsg = error.message ? error.message : error.toString();
    }
    console.error(errMsg);
    return Observable.throw(errMsg);
  }

}
